# -*- coding: utf-8 -*-

"""
工具库：gitmodules 解析
"""

import os


def parse(git_root, ignores=None):
    """
    从 .gitmodules 文件中解析出手册结构，获取 SUMMARY.md 文件列表

    似乎不能用 ConfigParser 解析
    import os, ConfigParser

    conf = ConfigParser.ConfigParser()
    conf.read([GITMODULES_PATH])
    print conf.sections()
    # print conf.options()
    """
    gitmodules_path = os.path.join(git_root, '.gitmodules')
    # print gitmodules_path
    # print '*' * 80
    # print open(gitmodules_path).read()
    with open(gitmodules_path) as _file:
        lines = [line.strip() for line in _file.read().split('\n')]
    lines = sorted([line.split('=')[1].strip() for line in lines if line.startswith('path =')])

    if isinstance(ignores, str):
        lines.remove(ignores)
    elif isinstance(ignores, (list, tuple, set)):
        for ignore in ignores:
            lines.remove(ignore)

    books = []
    for line in lines:
        summary_path = os.path.abspath(os.path.join(git_root, line, 'SUMMARY.md'))
        # print summary_path
        books.append(line)
        if not os.path.isfile(summary_path):
            print 'SummaryNotFound : %s, Now create it...' % summary_path
            with open(summary_path, 'w') as _file:
                _file.write('# SUMMARY\n\n* [概述](README.md)\n\n')

    return books
